const WebSocket = require('ws');
class RPC extends require('events'){
    constructor(options){
        super();
        this.ip='localhost';
        this.port=3001;
        this.conn=null;
        !!options&&Object.assign(this,options);
        this.connect();
    }
    //连接服务器
    connect(){
        this.conn = new WebSocket(`ws://${this.ip}:${this.port}`);

        this.conn.on('open', ()=> {
            console.log(`成功通过RPC连上服务器IP:${this.ip},端口:${this.port}`);
            this.emit('open');
        });

        this.conn.on('message', (data)=> {
            console.log(data);
            try{
                let JSON_Data=JSON.parse(data);
                this.emit('message',JSON_Data);
            }catch(e){
                consle.error(e);
            }

        });
        this.conn.on('error', ()=> {
            console.error(`rpc连接失败，服务器IP:${this.ip},端口:${this.port}`);
        });
    }
    //发送信息
    send(obj={}){
        this.conn.send(JSON.stringify(obj));
    }
    //发送需要等待回复的消息
    async request(){

    }
}

module.exports=RPC;